package com.bolt.auth.security.common.feign;


import feign.Logger;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2020/4/15.
 */
public class GolbalFeignConfig {
    @Bean
    Logger.Level feignLoggerLevel() {
        //这里记录所有，根据实际情况选择合适的日志level
        return Logger.Level.FULL;
    }

    @Bean
    public Encoder feignEncoder() {
        ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(getJacksonConverter());
        return new SpringEncoder(objectFactory);
    }

    @Bean
    public Decoder feignDecoder() {
        ObjectFactory <HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(getJacksonConverter());
        return new SpringDecoder(objectFactory);
    }

    private HttpMessageConverter getJacksonConverter() {
        FeignMappingJackson2HttpMessageConverter converter = new FeignMappingJackson2HttpMessageConverter();
        return converter;
    }

    public class FeignMappingJackson2HttpMessageConverter extends org.springframework.http.converter.json.MappingJackson2HttpMessageConverter {
        public FeignMappingJackson2HttpMessageConverter() {
            // 先将原先支持的MediaType列表拷出
            List<MediaType> mediaTypeList = new ArrayList<>(this.getSupportedMediaTypes());
            //加入对text/plain的支持
            mediaTypeList.add(new MediaType("text", "html", StandardCharsets.UTF_8));
            //将已经加入了text/json的MediaType支持列表设置为其支持的媒体类型列表
            this.setSupportedMediaTypes(mediaTypeList);
        }
    }

}

 